package com.jediflasher.game_server.services

import java.io.DataOutputStream
import com.jediflasher.game_server.core.events.EventDispatcher
import com.google.protobuf.Message
import com.jediflasher.game_server.messages.HeaderMessage.{ServiceType, Header, MessageType}
import com.jediflasher.game_server.util.log.Logger
import com.jediflasher.game_server.data.{SuperUserData, UserData, WorldData}

/**
 * User: Obi
 * Date: 14.07.11
 * Time: 20:56
 */

abstract class AbstractService(out: DataOutputStream, protected val worldData: WorldData, val superUser:SuperUserData) extends EventDispatcher {

	def superUserId = superUser.id;

	protected def send(message: Message = null, messageType: MessageType, method: Int, requestId: Int = 0) {
		var bodyLen: Int = 0;
		if (message != null) bodyLen = message.toByteArray.length;

		val header = Header.newBuilder()
				.setBodySize(bodyLen)
				.setMessageType(messageType)
				.setMethod(method)
				.setRequestId(requestId)
				.setServiceType(getServiceType)
				.setUserId(superUserId).build();

		// запишем длину сообщения
		val headerSize:Int = header.toByteArray.length;
		val totalSize:Int = headerSize + header.getBodySize + 4;
		out.writeInt(totalSize);

		Logger.log("output: "+totalSize + " bytes");

		out.writeInt(headerSize);

		header.writeTo(out); // запишем хедер
		message.writeTo(out); // запишем само сообщение

		out.flush();
	}

	def getServiceType: ServiceType;

}